<?php
/*
 * 用户操作类
 */
namespace Home\Logic;

class PassportLogic{

    private $pre = 'meiyehong';
    
    public function __construct() {
        $this->user = D('User');
    }
    
    public function getUserById($id){
        return $this->user->where('id='.$id)->find();
    }
    
    public function getUserByAccount($mobile){
        return $this->user->checkUser($mobile);
    }
    
    public function login($account,$password) {
        $re = $this->user->checkUser($account,$this->smcrypt($password));
        if($re['id']>0){
            $_SESSION['id'] = $re['id'];
            $_SESSION['time'] = time();
            $_SESSION['token'] = $this->formatSessionToken($_SESSION['time'], $re['id']);

            import('Logs', 'Log');
            $mongo = new \Log\Logs();
            $mongo->login_Log($re['id'],1);
            
        }
        return $re['id'];
    }
    
    public function addUser($name,$account,$password,$is_admin=1){
        return $this->user->addUser($name,$account,$this->smcrypt($password),$is_admin);
    }
    
    public function checkAccount($account){
        $user = $this->user->checkUser($account);
        if($user['id']>1){
            return false;
        }
        return true;
    }
    
    public function updateUser($data){
        if($data['id']<1){
            return false;
        }
        if(strlen($data['password'])>1){
            $data['password'] = $this->smcrypt($data['password']);
        }
        return $this->user->where('id='.$data['id'])->save($data);
    }
    
    public function updateUserByAccount($data){
        if(strlen($data['account'])!=11){
            return false;
        }
        if(strlen($data['password'])>1){
            $data['password'] = $this->smcrypt($data['password']);
        }
        return $this->user->where("account='".$data['account']."'")->save($data);
    }
    
    public function isLogin(){
        if($_SESSION['id']>0 && $_SESSION['time']>0 && $_SESSION['token'] == $this->formatSessionToken($_SESSION['time'], $_SESSION['id'])){
            return true;
        }
        return false;
    }
    
    public function getUser($id){
        if($this->isLogin()){
            return json_encode($this->user->field('user_name')->where(array('id'=>$_SESSION['id']))->find());
        }
        return false;
    }
    
    public function smcrypt($password){
        return md5(md5($password).$this->pre);
    }
    
    private function formatSessionToken($time,$id){
        return md5(md5($time).$id);
    }

    //后台admin 插入
    public function insertUser($data){
        $data['password'] = $this->smcrypt($data['password']);
        return $this->user->add($data);
    }

    //后台 admin 检查
    public function adminCheck($account){
        $where['account'] = $account;
        return $re = $this->user->where($where)->find();
    }
   
}
